<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<jsp:include page="common/header.jsp">
    <jsp:param name="title" value="商品列表"/>
    <jsp:param name="customCss" value="shop_list"/>
</jsp:include>

<div class="container">
    <div class="goods-list">
        <c:forEach items="${goodsList}" var="goods">
            <div class="goods-item">
                <div class="product-image-container">
                    <img src="${goods.imageData != null && goods.imageType != null ? 'data:image/'.concat(goods.imageType).concat(';base64,').concat(goods.imageData) : pageContext.request.contextPath.concat('/image/noproduct.png')}"
                         alt="${goods.name}"
                         class="product-image">
                </div>
                <div class="product-info">
                    <h3 class="product-name">${goods.name}</h3>
                    <p class="product-description">${goods.description}</p>
                    <div class="product-footer">
                        <p class="product-price">¥${goods.price}</p>
                        <p class="product-stock">库存: ${goods.stock}</p>
                        <button class="add-to-cart" onclick="addToCart(${goods.id})">
                            <i class="fas fa-shopping-cart"></i> 加入购物车
                        </button>
                    </div>
                </div>
            </div>
        </c:forEach>
    </div>
</div>

<div class="checkout-bar">
    <a href="${pageContext.request.contextPath}/toShopCartServlet" class="cart-link">
        <i class="fas fa-shopping-cart"></i> 去购物车结算
    </a>
</div>

<jsp:include page="common/footer.jsp">
    <jsp:param name="customJs" value="shop_list"/>
</jsp:include>

<script>
    function addToCart(goodsId) {
        const button = event.target.closest('button');
        const originalText = button.innerHTML;
        button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 添加中...';
        button.disabled = true;

        fetch('${pageContext.request.contextPath}/shopCartServlet', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=add&goodsId=' + goodsId + '&quantity=1'
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert('添加成功！');
                } else {
                    showAlert('添加失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('添加失败，请稍后重试');
            })
            .finally(() => {
                button.innerHTML = originalText;
                button.disabled = false;
            });
    }
</script>
<script src="${pageContext.request.contextPath}/js/modal.js"></script>
